package com.xishu.handler;

import cn.hutool.core.bean.BeanUtil;
import com.xishu.entity.customer.Customer;
import com.xishu.entity.customer.CustomerTicket;
import com.xishu.entity.customer.VipLevel;
import com.xishu.entity.member.Member;
import com.xishu.entity.shop.DiscountTicket;
import com.xishu.exception.ResponseStatusException;
import com.xishu.service.CommonService;
import com.xishu.service.CustomerService;
import com.xishu.service.DiscountTicketService;
import com.xishu.util.DateUtil;
import com.xishu.util.MongoId;
import com.xishu.util.Sha256Util;
import com.xishu.util.Tools;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 自定义处理器
 * 处理每一行数据读取
 */


public class SheetHandler implements XSSFSheetXMLHandler.SheetContentsHandler, Tools {

    private static Logger logger = LoggerFactory.getLogger(SheetHandler.class);
    private CommonService commonService = CommonService.getInstance();
    private CustomerService customerService=CustomerService.getInstance();

    private Member member;
    private Long companyId;

    private List<Member> list = new ArrayList<Member>();

    private static HashMap<String, String> map = new HashMap<>();

    static {
        map.put("2280611641179661", "食辣大俠九折");
        map.put("2280611641179693", "辣派掌門八五折");
        map.put("2280611641179740", "辣界宗師八折");
    }

    /**
     * 开始解析某一行的时候触发
     *
     * @param i
     */
    @Override
    public void startRow(int i) {
        if (i > 0) {
            member = new Member();
            member.setCompanyId(companyId);
        }
    }

    /**
     * 当结束某一行的时候触发
     *
     * @param i
     */

    @Override
    public void endRow(int i) {
        if (i > 0) {
            list.add(member);
        }
    }

    @Override
    public void endSheet() {
        for (Member member1 : list) {
            save(member1);
        }
    }

    private void save(Member member) {
        if (member.getMemberId() != null) {
            Customer customer = new Customer();
            customer.setPhone(member.getPhone());
            customer.setCompanyId(member.getCompanyId());
            Customer searchOne = commonService.searchOne(customer);
            String registerTime = member.getRegisterTime();

            long time = getTime(registerTime);
            if (!isNotEmpty(searchOne)) {
                BeanUtil.copyProperties(member, customer);
                customer.setCreateTime(time);

                try {
                    Optional<VipLevel> customerVipLevel = customerService.findCustomerVipLevel(customer.getScoreHistory(), companyId);
                    if (customerVipLevel.isPresent()){
                        customer.setVipLevelId(customerVipLevel.get().getId());
                    }
                } catch (ResponseStatusException e) {
                   logger.info("e",e);
                }

                //创建二维码
                String qrCode = MongoId.generateId();
                customer.setQrCode(qrCode);

                //生成二维码文件
                customerService.generateQrCode(qrCode);
                customer.setQrCodeImg(qrCode + ".png");
                try {
                    commonService.createObject(customer);
                } catch (Exception e) {
                    logger.error("customer error id {}", customer.getMemberId());
                }

                try {
                    //根据会员rank 确定发放的优惠券模板 rank 2280611641179661 模板名： 食辣大俠九折
                    String key = customer.getmRank();
                    String ticketName = map.get(key);

                    if (isNotEmpty(ticketName)) {
                        //查找出刚刚保存的会员对象，目的是找到会员的id，给ticket赋值
                        Customer cusDb = commonService.searchOne(customer);
                        CustomerTicket customerTicket = initCustomerTicket(cusDb, ticketName);
                        if (isNotEmpty(customerTicket)) {
                            commonService.createObject(customerTicket);
                        }
                    }
                } catch (Exception e) {
                    logger.error("e", e);
                }
            } else {
                logger.info("duplicate customer id {}", member.getPhone());
            }
        }
    }


    /**
     * 根据会员信息为优惠券赋值
     */
    private CustomerTicket initCustomerTicket(Customer cusDb, String ticketName) throws Exception {
        //根据优惠券名找出对应的优惠券模板
        DiscountTicket discountTicket = new DiscountTicket();
        discountTicket.setName(ticketName);
        discountTicket.setCompanyId(cusDb.getCompanyId());
        DiscountTicket discountTicketDd = commonService.searchOne(discountTicket);

        //有模板则创建
        if (isNotEmpty(discountTicketDd)) {

            //创建优惠券
            DiscountTicket realTicket = DiscountTicketService.getInstance().createRealTicket(discountTicketDd);
            realTicket.setAssignByExcel(true);
            realTicket.setStartTime(System.currentTimeMillis());
            realTicket.setEndTime(DateUtil.endTimeInDay(getTime(cusDb.getmRankExpireDate())));
            realTicket.setExpiredTime(DateUtil.endTimeInDay(getTime(cusDb.getmRankExpireDate())));
            if (System.currentTimeMillis() >= realTicket.getEndTime()) {
                realTicket.setExpired(true);
            }
            commonService.save(realTicket);

            //发放优惠券
            CustomerTicket customerTicket = new CustomerTicket();
            customerTicket.setParentTicketId(realTicket.getParentId());
            customerTicket.setCode(realTicket.getCode());
            customerTicket.setCompanyId(realTicket.getCompanyId());
            customerTicket.setCustomerId(cusDb.getId());
            customerTicket.setExpiredTime(realTicket.getEndTime());
            customerTicket.setTicketId(realTicket.getId());
            customerTicket.setAssignByExcel(true);
            if (System.currentTimeMillis() >= customerTicket.getExpiredTime()) {
                customerTicket.setExpired(true);
            }
            return customerTicket;
        } else {
            logger.info("ticket template is empty, send ticket fail ");
            return null;
        }
    }

    private long getTime(String registerTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(registerTime);
        } catch (ParseException e) {
            logger.info("e",e);
        }
        long time = parse.getTime();
        return time;
    }


    /**
     * 对行中每个表格进行处理
     *
     * @param cellReference 单元格名称
     * @param value         数据
     * @param xssfComment   批注
     */
    @Override
    public void cell(String cellReference, String value, XSSFComment xssfComment) {
        if (member != null) {
            String trim = value.trim();
            String pix = cellReference.substring(0, 1);
            switch (pix) {
                case "A":
                    member.setMemberId(trim);
                    break;
                case "E":
                    member.setNickName(trim);
                    break;
                case "L":
                    member.setPhone(trim);
                    member.setName(trim);
                    break;
                case "F":
                    member.setMRank(trim);
                    break;
                case "K":
                    member.setAreaCode(trim);
                    break;
                case "B":
                    member.setRegisterTime(trim);
                    break;
                case "H":
                    //1 男 2 女 对应 0 男 1女
                    if (trim.equals("0")) {
                        trim = "1";
                    } else {
                        trim = "2";
                    }
                    member.setSex(Integer.parseInt(trim));
                    break;
                case "I":
                    String birthday = trim;
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse = dateFormat.parse(birthday);
                        member.setBirthDay(parse.getTime());
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    String salt = Sha256Util.generateSalt();
                    String pass = birthdayToPass(birthday, salt);
                    member.setSalt(salt);
                    member.setPassword(pass);
                    break;
                case "R":
                    member.setScoreHistory(Integer.parseInt(trim));
                    break;
                case "S":
                    member.setScore(Integer.parseInt(trim));
                    break;
                case "O":
                    member.setMRankExpireDate(trim);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 密码加密
     *
     * @param birthday
     * @param salt
     * @return
     */
    private String birthdayToPass(String birthday, String salt) {
        String s = birthday.replaceAll("-", "").substring(0, 8);
        String sha256 = Sha256Util.sha256(s, salt);
        return sha256;
    }


    public void setCompanyId(Long companyId) {
        this.companyId = companyId;
    }
}
